#!/usr/bin/env bash
set -e

getkey () {
    target=${2:-/opt/docker/keys}
    [ ! -e $target ] && mkdir -p $target
    [ ! -d $target ] && {
        mv $target ${target}.old && mkdir $target
    }
    ca=ca.pem
    [ -z "$1" ] && {
        echo "please specify the host for new key pair: [default]"
        read host
    }
    host=${1:-default}
    scp root@ca.revolc.xyz:/root/CA/ca.pem ${target}/ca.pem
    scp root@ca.revolc.xyz:/root/CA/${host}-cert.pem ${target}/cert.pem
    scp root@ca.revolc.xyz:/root/CA/${host}-priv-key.pem ${target}/key.pem

    [ -n "$2" ] && return 0

    opt=/etc/default/docker
    if [ -e ${opt} ] ; then
        sh $opt
    else
        DOCKER_OPTS=""
    fi

    options=
    for o in $DOCKER_OPTS ;do
        [ "${o:0:2}" == "-H" ] && shift 2
        [ "${o:0:12}" == "--tlsverify=" ] && shift 1
        [ "${o:0:12}" == "--tlscacert=" ] && shift 1
        [ "${o:0:10}" == "--tlscert=" ] && shift 1
        [ "${o:0:9}" == "--tlskey=" ] && shift 1
        [ "${o}" == "--tlsverify" ] && shift 2
        [ "${o}" == "--tlscacert" ] && shift 2
        [ "${o}" == "--tlscert" ] && shift 2
        [ "${o}" == "--tlskey" ] && shift 2
        options="$options $o"
    done
    options="$options -H $host:2376"
    options="$options --tlsverify"
    options="$options --tlscacert=${target}/ca.pem"
    options="$options --tlscert=${target}/cert.pem"
    options="$options --tlskey=${target}/key.pem"

    DOCKER_OPTS=$options
    echo "DOCKER_OPTS=\"$DOCKER_OPTS\"">$opt
    echo Following options has been written into $opt:
    echo DOCKER_OPTS: $DOCKER_OPTS
    source $opt

    service docker stop
    docker $DOCKER_OPTS daemon &
}
getkey $*